"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { ArrowLeft, Save, Loader2 } from "lucide-react";
import Link from "next/link";
import { API_ENDPOINTS, authenticatedRequest } from "@/lib/api";
import { getAuthFromStorage } from "@/lib/auth";
import { useApiMutation } from "@/lib/useApiMutation";

interface CreatePostData {
  title: string;
  slug: string;
  content: string;
  excerpt?: string;
  coverImage?: string;
  authorId: string;
}

export default function NewPostPage() {
  const auth = getAuthFromStorage();
  const [formData, setFormData] = useState<CreatePostData>({
    title: "",
    slug: "",
    content: "",
    excerpt: "",
    coverImage: "",
    authorId: auth.user?.id || "",
  });
  const router = useRouter();

  // React Query mutation 封装
  const { mutate: createPost, isPending } = useApiMutation(
    (data: CreatePostData) =>
      authenticatedRequest(API_ENDPOINTS.POSTS, {
        method: "POST",
        body: JSON.stringify(data),
      }),
    {
      onSuccess: () => {
        router.push("/posts");
      },
    }
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createPost(formData);
  };

  const handleTitleChange = (value: string) => {
    setFormData((prev) => ({
      ...prev,
      title: value,
      slug: value
        .toLowerCase()
        .replace(/[^a-z0-9\s-]/g, "")
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-")
        .trim(),
    }));
  };

  useEffect(() => {
    const auth = getAuthFromStorage();
    setFormData((prev) => ({
      ...prev,
      authorId: auth.user?.id || "",
    }));
    if (!auth.isAuthenticated) {
      router.push("/login");
      return;
    }
  }, [router]);

  if (!auth.isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p>检查登录状态...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* 返回按钮 */}
        <div className="mb-6">
          <Link href="/posts">
            <Button variant="outline" size="sm">
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回文章列表
            </Button>
          </Link>
        </div>

        {/* 发布文章表单 */}
        <Card>
          <CardHeader>
            <CardTitle>发布新文章</CardTitle>
            <CardDescription>填写文章信息，发布您的精彩内容</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="title">文章标题 *</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => handleTitleChange(e.target.value)}
                  placeholder="请输入文章标题"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="slug">文章链接 *</Label>
                <Input
                  id="slug"
                  value={formData.slug}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, slug: e.target.value }))
                  }
                  placeholder="文章的唯一链接"
                  required
                />
                <p className="text-sm text-gray-500">
                  这将作为文章的访问链接，建议使用英文和连字符
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="excerpt">文章摘要</Label>
                <Textarea
                  id="excerpt"
                  value={formData.excerpt}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      excerpt: e.target.value,
                    }))
                  }
                  placeholder="请输入文章摘要"
                  rows={3}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="coverImage">封面图片链接</Label>
                <Input
                  id="coverImage"
                  value={formData.coverImage}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      coverImage: e.target.value,
                    }))
                  }
                  placeholder="请输入封面图片链接"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="content">文章内容 *</Label>
                <Textarea
                  id="content"
                  value={formData.content}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      content: e.target.value,
                    }))
                  }
                  placeholder="请输入文章内容"
                  rows={15}
                  required
                />
              </div>

              <div className="flex justify-end space-x-4">
                <Link href="/posts">
                  <Button type="button" variant="outline">
                    取消
                  </Button>
                </Link>
                <Button type="submit" disabled={isPending}>
                  {isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      发布中...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      发布文章
                    </>
                  )}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
